package com.poisonh.unifiedauth.ui;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.zxing.Result;
import com.lzy.okhttputils.model.HttpParams;
import com.poisonh.unifiedauth.R;
import com.poisonh.unifiedauth.dialog.ScanCodePopWindow;
import com.poisonh.unifiedauth.utils.ConstantUitls;
import com.poisonh.unifiedauth.utils.MyHttpsUtils;
import com.poisonh.unifiedauth.utils.ToastUtils;
import com.poisonh.unifiedauth.zxing.decode.DecodeThread;
import com.poisonh.unifiedauth.zxing.decode.Utils;
import com.poisonh.unifiedauth.zxing.utils.Constant;
import com.poisonh.unifiedauth.zxing.utils.ScanListener;
import com.poisonh.unifiedauth.zxing.utils.ScanManager;
import com.poisonh.unifiedauth.zxing.utils.XiaomiUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 扫一扫
 * Created by PoisonH on 2016/6/29.
 */
public class ScanQRCodeActivty extends BaseActivity implements ScanListener, View.OnClickListener, ScanCodePopWindow.ClickPositionListener
{
    private SurfaceView scanPreview = null;
    private View scanContainer;
    private View scanCropView;
    private ImageView scanLine;
    private ScanManager scanManager;
    final int PHOTOREQUESTCODE = 1111;
    private int scanMode;//扫描模型（条形，二维码，全部）

    private String mStrUUID;
    private String mStrAppId;
    private String mStrSite;
    private String str[];

    //第三方授权登录标示或者开发者授权登录标示
    public static int SCAN_RESULT_AUTHTHIRDAPP_MARK = 10001;
    //扫描查询用户信息标示
    public static int SCAN_RESULT_AUTHMYAPP_MARK = 10002;
    //其他扫描结果信息标示
    public static int SCAN_RESULT_OTHERRESULTS_MARK = 10003;
    //扫描二维码显示card结果
    public static int SCAN_RESULT_CARD_MARK = 10004;

    // 要申请的权限
    private String[] permissions = {Manifest.permission.CAMERA};
    private AlertDialog dialog;
    private static final int PERMISSION_REQUEST_CAMERA= 1;
    private static final int PERMISSION_REQUESTCODE_CAMERA= 2;
    @Override
    protected void loadContentView(Bundle savedInstanceState)
    {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_qrcode);
        initTitleView();
        setTitleTxt("安全扫一扫");
        initView();

        // 版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            // 检查该权限是否已经获取
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (ContextCompat.checkSelfPermission(this, permissions[0]) != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                // showDialogTipUserRequestPermission();
                startRequestPermission();
            }else {
               // Toast.makeText(this, "权限授予成功了??", Toast.LENGTH_SHORT).show()

            }
        }
    }

    @Override
    protected void initView()
    {
        mLeftBtn.setOnClickListener(this);
        scanMode = getIntent().getIntExtra(Constant.REQUEST_SCAN_MODE, Constant.REQUEST_SCAN_MODE_ALL_MODE);
        scanPreview = (SurfaceView) findViewById(R.id.capture_preview);
        scanLine = (ImageView) findViewById(R.id.capture_scan_line);
        scanContainer = findViewById(R.id.capture_container);
        scanCropView = findViewById(R.id.capture_crop_view);
        //构造出扫描管理器
        scanManager = new ScanManager(this, scanPreview, scanContainer, scanCropView, scanLine, scanMode, this);
        mRightBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.ib_right_btn:
                showPopupWindow();
                break;
            case R.id.ib_left_btn:
                finish();
                break;
        }
    }

    // 开始提交请求权限
    private void startRequestPermission() {
        ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST_CAMERA);
    }
//
//
//    // 用户权限 申请 的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == PERMISSION_REQUEST_CAMERA) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                    boolean b = shouldShowRequestPermissionRationale(permissions[0]);
                    if (!b) {  //360手机一直都是返回false  所以不会执行下面的方法
                        // 用户还是想用我的 APP 的
                        // 提示用户去应用设置界面手动开启权限
                        showDialogTipUserGoToAppSettting();
                    } else
                        finish();
                } else {
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    // 提示用户去应用设置界面手动开启权限

    private void showDialogTipUserGoToAppSettting() {

        dialog = new AlertDialog.Builder(this)
                .setTitle("相机权限不可用")
                .setMessage("请在-应用设置-权限-中，允许年轮使用相机权限!否则，您将无法正常使用年轮!")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用设置界面
                        goToAppSetting();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false).show();
    }

    // 跳转到当前应用的设置界面
    private void goToAppSetting() {
        Intent intent = new Intent();

        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);

        startActivityForResult(intent, PERMISSION_REQUESTCODE_CAMERA);
    }

    private void showPopupWindow()
    {
        ScanCodePopWindow popWindow = new ScanCodePopWindow(this);
        popWindow.showPopupWindow(mRightBtn);
    }

    /**
     * 扫描结果
     *
     * @param rawResult 结果对象
     * @param bundle    存放了截图，或者是空的
     */
    @Override
    public void scanResult(final Result rawResult, final Bundle bundle)
    {
        if (!scanManager.isScanning())
        {
            Bitmap barcode = null;
            byte[] compressedBitmap = bundle.getByteArray(DecodeThread.BARCODE_BITMAP);
            if (compressedBitmap != null)
            {
                barcode = BitmapFactory.decodeByteArray(compressedBitmap, 0, compressedBitmap.length, null);
                barcode = barcode.copy(Bitmap.Config.ARGB_8888, true);

            }
        }

        rawResult.toString();
        str = rawResult.toString().trim().split(",");

        if (str.length == 3 && str[0].equals("Certification"))
        {
           scanQueryUserInfo();//扫描查询用户信息


        } else
        {

            Pattern pa = Pattern.compile("(.*)\\?");
            Matcher m = pa.matcher(rawResult.toString());
            while (m.find())
            {
                mStrSite = m.group(1);
            }
            if (mStrSite == null)
            {
                returnOtherResults(rawResult.toString());//返回其他扫描结果
                return;
            } else
            {

                if (mStrSite.equals(ConstantUitls.SCAN_CODE_MARK))
                {
                    Pattern p = Pattern.compile("uuid=(.*)&");
                    Matcher matcher = p.matcher(rawResult.toString());
                    while (matcher.find())
                    {
                        mStrUUID = matcher.group(1);
                    }

                    Pattern p2 = Pattern.compile("app_id=(.*)");
                    Matcher matcher2 = p2.matcher(rawResult.toString());

                    if (matcher2.find())
                    {
                        mStrAppId = matcher2.group(1);
                        authThirdApp();
                    } else
                    {
                        authMyApp();
                    }

                } else
                {
                    returnOtherResults(rawResult.toString());
                    //  ToastUtils.showToast(ScanQRCodeActivty.this, rawResult.toString());
                    return;
                }
            }
        }
    }

    /**
     * 第三方授权登录
     */
    private void authThirdApp()
    {
        HttpParams params = new HttpParams();
        params.put("user_id", mStrUserId);
        params.put("app_id", mStrAppId);
        params.put("uuid", mStrUUID);
        MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.BINDING, params, new MyHttpsUtils.ResultCallback()
        {
            @Override
            public void onSuccess(String response)
            {
                try
                {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONObject data = jsonObject.getJSONObject("results");
                    String app_name = data.getString("app_name");
                    String app_img = data.getString("app_img");
                    Intent resultIntent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putString("app_id", mStrAppId);
                    bundle.putString("uuid", mStrUUID);
                    bundle.putString("app_name", app_name);
                    bundle.putString("app_img", app_img);
                    resultIntent.putExtras(bundle);
                    ScanQRCodeActivty.this.setResult(SCAN_RESULT_AUTHTHIRDAPP_MARK, resultIntent);
                    ScanQRCodeActivty.this.finish();
                }
                catch (JSONException e)
                {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String failReason)
            {
                ToastUtils.showToast(ScanQRCodeActivty.this, "拉取授权失败");
                ScanQRCodeActivty.this.finish();
            }
        });
    }

    /***
     * 开发者授权登录
     */
    private void authMyApp()
    {
        HttpParams params = new HttpParams();
        params.put("userid",mStrUserId);
        params.put("token", mStrUserToken);
        params.put("uuid", mStrUUID);
        MyHttpsUtils.post(ConstantUitls.AUTH_MYAPP_URL + ConstantUitls.VER_AUTH_MYAPP, params, new MyHttpsUtils.ResultCallback()
        {
            @Override
            public void onSuccess(String response)
            {
                try
                {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONObject data = jsonObject.getJSONObject("results");
                    String app_name = data.getString("app_name");
                    String app_img = data.getString("app_img");
                    Intent resultIntent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putString("app_id", "A");
                    bundle.putString("uuid", mStrUUID);
                    bundle.putString("app_name", app_name);
                    bundle.putString("app_img", app_img);
                    resultIntent.putExtras(bundle);
                    ScanQRCodeActivty.this.setResult(SCAN_RESULT_AUTHTHIRDAPP_MARK, resultIntent);
                    ScanQRCodeActivty.this.finish();
                } catch (JSONException e)
                {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String failReason)
            {
                ToastUtils.showToast(ScanQRCodeActivty.this, "拉取授权失败");
                ScanQRCodeActivty.this.finish();
            }
        });
    }

    /**
     * 扫描查询用户信息
     */
    private void scanQueryUserInfo()
    {

        HttpParams params = new HttpParams();
        params.put("token", mStrUserToken);
        //扫描用户id
        params.put("scanning_userId",mStrUserId);
        //被扫描用户id
        params.put("tobe_scanning_userId", str[1]);
        //令牌
        params.put("truncated", str[2]);
        MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.VALIDATIONQRCODE, params, new MyHttpsUtils.ResultCallback()
        {
            @Override
            public void onSuccess(String response)
            {
                try
                {
                    JSONObject object = new JSONObject(response);
                    String code=object.getString("code");
                    if("200".equals(code)){
                        JSONObject data = object.getJSONObject("results");
                        if(!data.isNull("businessCard")){
                            JSONObject card=data.getJSONObject("businessCard");
                            Intent mIntent = new Intent();
                            Bundle mBundle = new Bundle();
                            mBundle.putString("COMPANY", card.getString("company"));//公司名称
                            mBundle.putString("EMAIL", card.getString("email"));//email
                            mBundle.putString("HEADIMG", card.getString("headImg"));//头像
                            mBundle.putString("ID", card.getString("id"));//id
                            mBundle.putString("MOBILE", card.getString("mobile"));//手机号
                            mBundle.putString("NAME", card.getString("name"));//姓名昵称
                            mBundle.putString("UID", card.getString("uid"));//uid
                            mBundle.putString("token", mStrUserToken);
                            //扫描用户id
                            mBundle.putString("scanning_userId",mStrUserId);

//                        mBundle.putString("CARD", card.getString("card"));
//                        mBundle.putString("REALNAME", card.getString("realName"));
                            mIntent.putExtras(mBundle);
                            ScanQRCodeActivty.this.setResult(SCAN_RESULT_CARD_MARK, mIntent);
                            ScanQRCodeActivty.this.finish();
                        }else {
                            //为空的时候取值
                            Intent mIntent = new Intent();
                            Bundle mBundle = new Bundle();
                            mBundle.putString("CARD", data.getString("card"));
                            mBundle.putString("REALNAME", data.getString("realName"));
                            mIntent.putExtras(mBundle);
                            ScanQRCodeActivty.this.setResult(SCAN_RESULT_AUTHMYAPP_MARK, mIntent);
                            ScanQRCodeActivty.this.finish();
                        }

                    }else if("201".equals(code)){
                       // Toast.makeText(ScanQRCodeActivty.this,"此用户已经添加到名片夹，不能再次添加",Toast.LENGTH_SHORT).show();
                        ToastUtils.showToast(ScanQRCodeActivty.this, "此用户已经添加到名片夹，不能再次添加");
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                scanManager.reScan();
                            }
                        },2000);
                    }



                } catch (JSONException e)
                {
                    e.printStackTrace();
                }
                Log.d("AAA", response);
                //ToastUtils.showToast(ScanQRCodeActivty.this, response);
            }

            @Override
            public void onFailure(String failReason)

            {
                Log.d("AAA", failReason);
                ToastUtils.showToast(ScanQRCodeActivty.this, failReason);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        scanManager.reScan();
                    }
                },2000);
            }
        });
    }

    /**
     * 扫描二维码获取用户名片信息(暂时没用)
     */
    public   void QueryCardInfo()
    {

        HttpParams params = new HttpParams();
        params.put("token", mStrUserToken);
        //扫描用户id
        params.put("userId",mStrUserId);
        //被扫描用户id
        params.put("destId", str[1]);
        MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.CARDUSER, params, new MyHttpsUtils.ResultCallback()
        {
            @Override
            public void onSuccess(String response)
            {
                try
                {
                    JSONObject object = new JSONObject(response);
                    JSONObject data = object.getJSONObject("results");
                    Intent mIntent = new Intent();
                    Bundle mBundle = new Bundle();
                    mBundle.putString("CARD", data.getString("card"));
                    mBundle.putString("REALNAME", data.getString("realName"));
                    mIntent.putExtras(mBundle);
                    ScanQRCodeActivty.this.setResult(SCAN_RESULT_AUTHMYAPP_MARK, mIntent);
                    ScanQRCodeActivty.this.finish();

                } catch (JSONException e)
                {
                    e.printStackTrace();
                }
                Log.d("AAA", response);
            }

            @Override
            public void onFailure(String failReason)

            {
                Log.d("AAA", failReason);
            }
        });
    }




    /**
     * 返回其他扫描结果
     *
     * @param otherresults
     */
    private void returnOtherResults(String otherresults)
    {
        Intent mIntent = new Intent();
        Bundle mBundle = new Bundle();
        mBundle.putString("OTHERSULTS", otherresults);
        mIntent.putExtras(mBundle);
        ScanQRCodeActivty.this.setResult(SCAN_RESULT_OTHERRESULTS_MARK, mIntent);
        ScanQRCodeActivty.this.finish();
    }

    @Override
    public void scanError(Exception e)
    {
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        //相机扫描出错时
        if (e.getMessage() != null && e.getMessage().startsWith("相机"))
        {
            scanPreview.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        scanManager.onResume();
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        scanManager.onPause();
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        scanManager.onDestroy();
    }

    public void showPictures(int requestCode)
    {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, requestCode);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK)
        {
            switch (requestCode)
            {
                case PHOTOREQUESTCODE:
                    cursorPath(data);
                    break;
            }
        }
        switch (requestCode)
        {
            case PERMISSION_REQUESTCODE_CAMERA:
                if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    // 检查该权限是否已经获取
//                        int i = ContextCompat.checkSelfPermission(this, permissions[0]);
                    // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                   // PERMISSION_GRANTED
                    if ( ContextCompat.checkSelfPermission(this, permissions[0]) != PackageManager.PERMISSION_GRANTED) {
                        // 提示用户应该去应用设置界面手动开启权限
                        showDialogTipUserGoToAppSettting();
                        // Settings.System.canWrite(this);
                    } else {
                       // Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                        }

                    }
                }
                break;
        }

    }

    /**
     * cursor路径
     *
     * @param data
     */
    private void cursorPath(Intent data)
    {
        try
        {
            String[] proj = {MediaStore.Images.Media.DATA};
            Uri muri = XiaomiUtils.geturi(data, ScanQRCodeActivty.this);
            Cursor cursor = this.getContentResolver().query(muri, proj, null, null, null);
            if (cursor.moveToFirst())
            {
                int colum_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                String photo_path = cursor.getString(colum_index);
                if (photo_path == null)
                {
                    photo_path = Utils.getPath(getApplicationContext(), data.getData());
                }
                scanManager.scanningImage(photo_path);
                cursor.close();
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public void onClickPosition(int pos)
    {
        if (pos == 0)
        {
            showPictures(PHOTOREQUESTCODE);
        } else if (pos == 1)
        {
            startActivity(new Intent(ScanQRCodeActivty.this, QrHelpActvity.class));
        }
    }
}
